package com.qiangqiang.task.server.service;

import com.qiangqiang.task.server.consts.TimeConst;
import com.qiangqiang.task.server.dto.MessageDTO;
import com.qiangqiang.task.server.mapper.UserMapper;
import com.qiangqiang.task.server.util.JsonUtil;
import com.qiangqiang.task.server.util.TimeFormat;
import com.qiangqiang.task.server.websocket.MyHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

/**
 * @program: task
 * @description:
 * @author: Sky.lin
 * @create: 2019-03-04 14:21
 **/
@Service
public class NotificationService {
    @Autowired
    private MyHandler myHandler;
    @Autowired
    private UserMapper userMapper;


    public <T> void notifyUser(long fromId, long toId, int type, T message) {
        String name = userMapper.queryNickNameByUserId(fromId);
        String time = TimeFormat.converTime(TimeConst.nowTimeMilli);
        MessageDTO dto = new MessageDTO(name, time, message);
        dto.setType(type);
        TextMessage textMessage = new TextMessage(JsonUtil.beanToString(dto));
        myHandler.sendMessageToUser(String.valueOf(toId), textMessage);
    }

    public <T> void notifyUser(long fromId, long toId, String commonId, T message) {
        String name = userMapper.queryNickNameByUserId(fromId);
        String time = TimeFormat.converTime(TimeConst.nowTimeMilli);
        MessageDTO dto = new MessageDTO(name, time, message);
        dto.setCommonId(commonId);
        dto.setType(1);
        TextMessage textMessage = new TextMessage(JsonUtil.beanToString(dto));
        myHandler.sendMessageToUser(String.valueOf(toId), textMessage);
    }

}
